package com.googlecode.jtoy.mybatis.mybatis;

import java.io.Reader;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.log4j.Logger;

/**
 * @author shangxj
 * @date May 20, 2011 3:19:46 PM
 */
public class MyBatisHelper {

	public static final Logger log = Logger.getLogger(MyBatisHelper.class);

	private static String config = "com/googlecode/jtoy/mybatis/mybatis/mybatis-config.xml";

	private static SqlSessionFactory factory;

	/**
	 * 获得MyBatis SqlSessionFactory
	 */
	public static SqlSessionFactory getSessionFactory() {

		if (factory != null) return factory;

		Reader reader = null;
		try {
			reader = Resources.getResourceAsReader(config);
		}
		catch (Exception e) {
			log.error("can not read config file" + config);
			if (log.isDebugEnabled()) {
				e.printStackTrace();
			}
		}
		factory = new SqlSessionFactoryBuilder().build(reader);
		return factory;
	}

	/**
	 * 打开MyBatis SqlSession
	 */
	public static SqlSession openSession() {

		return getSessionFactory().openSession();
	}

}
